import {_decorator} from 'cc';
import {
    CONTROLLER_ENUM,
    DIRECTION_ENUM,
    DIRECTION_ORDER_ENUM,
    ENTITY_STATE_ENUM,
    ENTITY_TYPE_ENUM,
    EVENT_ENUM
} from "../../Enums";
import EventManager from "../../Runtime/EventManager";
import {PlayerStateMachine} from "./PlayerStateMachine";
import {EntityManager} from "../../Base/EntityManager";
import DataManager from "../../Runtime/DataManager";

const { ccclass, property } = _decorator;

@ccclass('PlayerManager')
export class PlayerManager extends EntityManager {
    targetX:number = 2;
    targetY:number = 2;
    private readonly speed = 1/10;

    async init() {
        this.fsm = this.addComponent(PlayerStateMachine);
        await this.fsm.init();

        super.init({
            x:10,
            y:0,
            type: ENTITY_TYPE_ENUM.PLAYER,
            direction: DIRECTION_ENUM.TOP,
            state: ENTITY_STATE_ENUM.IDLE
        });
        EventManager.Instance.on(EVENT_ENUM.PLAYER_CONTROL, this.inputHandler, this);
    }

    update() {
        this.updateXY();
        super.update();
    }
    updateXY() {
        if(this.x < this.targetX)
            this.x += this.speed;
        else if(this.x > this.targetX)
            this.x -= this.speed;
        if(this.y < this.targetY)
            this.y += this.speed;
        else if(this.y > this.targetY)
            this.y -= this.speed;

        if(Math.abs(this.x - this.targetX) < 0.1)
            this.x = this.targetX;
        if(Math.abs(this.y - this.targetY) < 0.1)
            this.y = this.targetY;

    }

    inputHandler(inputDirection: CONTROLLER_ENUM) {
        if(this.willBlock(inputDirection)){
            return;
        }
        this.move(inputDirection);
    }

    willBlock(inputDirection: CONTROLLER_ENUM) {
        return true;
    }

    move(inputDirection: CONTROLLER_ENUM) {
        console.log(DataManager.Instance.tileInfo)
        switch (inputDirection) {
            case CONTROLLER_ENUM.TOP:
                this.targetY -=1;
                break;
            case CONTROLLER_ENUM.BOTTOM:
                this.targetY +=1;
                break;
            case CONTROLLER_ENUM.LEFT:
                this.targetX -=1;
                break;
            case CONTROLLER_ENUM.RIGHT:
                this.targetX +=1;
                break;
            case CONTROLLER_ENUM.TURNLEFT:
                this.state = ENTITY_STATE_ENUM.TURNLEFT;
                //上左下右
                this.direction = DIRECTION_ENUM[DIRECTION_ORDER_ENUM[(DIRECTION_ORDER_ENUM[this.direction] + 1) % 4]]
                break;
            case CONTROLLER_ENUM.TURNRIGHT:
                this.state = ENTITY_STATE_ENUM.TURNRIGHT;
                this.direction = DIRECTION_ENUM[DIRECTION_ORDER_ENUM[(DIRECTION_ORDER_ENUM[this.direction] + 3) % 4]]
                break;

        }

    }

}

